package group.rober.jeki.admin.controller

import group.rober.jeki.entity.Tag
import group.rober.jeki.service.ArticleService
import group.rober.jeki.service.TagService
import group.rober.saber.kit.NumberKit
import group.rober.saber.kit.StringKit
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.ModelAttribute
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.servlet.ModelAndView

@Controller
@RequestMapping("/admin")
class AdminTagController {
    @Autowired
    TagService tagService;
    @Autowired
    ArticleService articleService;

    @RequestMapping("/tag-list")
    ModelAndView tagList() {
        Map<String, Object> vars = new HashMap<String, Object>();
        return new ModelAndView("views/admin/tag-list", [
                "tagList"          : tagService.getTagList()
                , "tag"            : new Tag()
        ]);
    }

//    @RequestMapping("/tag-create")
//    ModelAndView tagCreate() {
//        Tag tag = new Tag();
//        return new ModelAndView("views/admin/tag-editor", ["tag": tag]);
//    }

    @RequestMapping("/tag/{tagId}")
    ModelAndView tagEditor(@PathVariable("tagId") String tagId) {
        Tag tag = tagService.getTag(tagId);
        return new ModelAndView("views/admin/tag-editor", ["tag": tag]);
    }

    @RequestMapping("/tag/delete-action/{tagId}")
    ModelAndView tagDelete(@PathVariable("tagId") String tagId) {
        Tag tag = tagService.getTag(tagId);
        tagService.deleteTag(tag);
        return new ModelAndView("redirect:/admin/tag-list");
    }

    @RequestMapping(path = "/tag/save-action", method = RequestMethod.POST)
    ModelAndView tagSaveAction(@ModelAttribute Tag tag) {
        if (StringKit.isBlank(tag.getId())) {
            tag.setId(NumberKit.nanoTime36());
        }
        if(StringKit.isBlank(tag.getCode())){
            tag.setCode(tag.getName());
        }
        tagService.saveTag(tag);
        return new ModelAndView("redirect:/admin/tag-list");
    }
    @RequestMapping(path = "/tag/statistics-action", method = RequestMethod.GET)
    ModelAndView statisticsTagAction() {
        articleService.statisticsArticleTag();
        return new ModelAndView("redirect:/admin/tag-list");
    }
}
